package com.own.component.store.local.method.state;

import java.io.Serializable;
import java.time.Duration;

/**
 * StateExpire
 *
 * @author chenxueli
 * @date 2023-07-10 16:16:55
 */
public class StateExpire<T> implements Serializable {

    private final T state;

    private long expire;

    public StateExpire(T state, long timeout) {
        this(state, Duration.ofMillis(timeout));
    }

    public StateExpire(T state, Duration duration) {
        this.state = state;
        this.expire = System.currentTimeMillis() + duration.toMillis();
    }

    /**
     * 是否过期
     *
     * @return 是否过期
     */
    public boolean isExpired() {
        return System.currentTimeMillis() > this.expire;
    }

    /**
     * 设置过期时间
     *
     * @param timeout 过期时间
     */
    public void setExpire(long timeout) {
        setExpire(Duration.ofMillis(timeout));
    }

    /**
     * 设置过期时间
     *
     * @param duration 过期时间
     */
    public void setExpire(Duration duration) {
        this.expire = System.currentTimeMillis() + duration.toMillis();
    }

    /**
     * 获取值
     *
     * @return 值
     */
    public T getState() {
        if (isExpired()) {
            return null;
        }
        return state;
    }

}
